package cn.edu.swu.common;

import cn.edu.swu.modal.Book;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBTools {
    public static List<Book> getAllBook(){
        List<Book> result = new ArrayList<>();
        String sql="select id,name,author,price,content from book";
        try(Connection connection = getConnection()){
            try (Statement statement = connection.createStatement()) {
                try (ResultSet resultSet = statement.executeQuery(sql)) {
                    while (resultSet.next()) {
                        int id = resultSet.getInt("id");
                        String name = resultSet.getString("name");
                        String author = resultSet.getString("author");
                        float price = resultSet.getFloat(4);
                        String content = resultSet.getString(5);

                        Book book = new Book(id, name, author, price, content);
                        result.add(book);
                    }
                }
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static Connection getConnection() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.cj.jdbc.Driver");
        String dbUrl="jdbc:mysql://127.0.0.1:3306/bookstore";
        String dbUser="root";
        String dbPass="123456";

        return DriverManager.getConnection(dbUrl, dbUser, dbPass);
    }
}
